package com.maint.m.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.maint.m.NetworkUtils
import com.maint.m.SaveTicketResponse
import com.maint.m.TicketApiService
import com.maint.m.UpdateStatusRequest

class VideoViewModel : ViewModel() {
    private val TAG = "VideoViewModel"
    
    val isLoading = MutableLiveData<Boolean>()
    val errorMessage = MutableLiveData<String?>(null)
    val updateSuccess = MutableLiveData<Boolean>()
    
    fun updateTicketStatus(ticketId: String, status: String) {
        isLoading.postValue(true)
        errorMessage.postValue(null)
        updateSuccess.postValue(false)
        
        val apiService = NetworkUtils.createService(TicketApiService::class.java)
        val call = apiService.updateTicketStatus(UpdateStatusRequest(ticketId, status))
        
        call.enqueue(object : retrofit2.Callback<SaveTicketResponse> {
            override fun onResponse(
                call: retrofit2.Call<SaveTicketResponse>,
                response: retrofit2.Response<SaveTicketResponse>
            ) {
                isLoading.postValue(false)
                
                if (response.isSuccessful && response.body()?.statusCode == "200") {
                    Log.i(TAG, "更新状态成功: ${response.body()?.message}")
                    updateSuccess.postValue(true)
                } else {
                    val errorMsg = response.body()?.message ?: response.message() ?: "更新失败"
                    Log.e(TAG, "更新状态失败: $errorMsg")
                    errorMessage.postValue("更新状态失败: $errorMsg")
                }
            }
            
            override fun onFailure(call: retrofit2.Call<SaveTicketResponse>, t: Throwable) {
                isLoading.postValue(false)
                Log.e(TAG, "网络请求失败", t)
                errorMessage.postValue("网络错误: ${t.message}")
            }
        })
    }
}